<?php

namespace App\Http\Controllers\Admin\Customer;

use App\Http\Controllers\Controller;
use App\Models\cainiao\NotifyModel;
use App\Models\lazada\NodeRecordModel ;
use Illuminate\Http\Request;

class NodeRecord extends Controller
{

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $customer_id = $request->input('customer_id', '');
        $node_id = $request->input('node_id', '');
        $bigBagID = $request->input('bigBagID', '');
        $logisticsOrderCode = $request->input('logisticsOrderCode', '');
        $trackingNumber = $request->input('trackingNumber', '');
        $take_order_sn = $request->input('take_order_sn', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = NodeRecordModel::query()->with(['create_user', 'node', 'customer']);

        if($customer_id){
            $query = $query->where('customer_id', $customer_id);
        }

        if($node_id){
            $query = $query->where('node_id', $node_id);
        }

        if($bigBagID){
            $query = $query->where('bigBagID', $bigBagID);
        }

        if($logisticsOrderCode){
            $query = $query->where('logisticsOrderCode', $logisticsOrderCode);
        }

        if($trackingNumber){
            $query = $query->where('trackingNumber', $trackingNumber);
        }

        if($take_order_sn){
            $query = $query->where('take_order_sn', $take_order_sn);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'customer_name' => $item->customer->name ?? '',
                'update_type' => NodeRecordModel::TYPES[$item->type] ?? '',
                'record_type' => NodeRecordModel::RECORD_TYPES[$item->record_type] ?? '',
                'bigBagID' => $item->bigBagID,
                'logisticsOrderCode' => $item->orderCode,
                'trackingNumber' => $item->trackingNumber,
                'take_order_sn' => $item->take_order_sn,
                'node_name' => $item->node->name_cn ?? '',
                'created_admin_name' => $item->create_user->name ?? '',
                'created_at' => $item->created_at->toDateTimeString()
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


}
